package boot.spring.schedule;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.github.pagehelper.StringUtil;

import boot.spring.po.City;
import boot.spring.repository.CityRepository;
import boot.spring.service.CityService;


@Component
public class ScheduledTasks {
	@Autowired
	CityService cityService;

	@Autowired
	CityRepository cityRepository;
	
	public static ThreadPoolExecutor es = new ThreadPoolExecutor(50, 100, 0L, TimeUnit.SECONDS,new LinkedBlockingQueue());
	
	// 一分钟轮询一次数据库
	@Scheduled(cron = "0 */1 * * * ?")
	public void reportCurrentTime() throws Exception {
		String content = null;
		int size = 0;
		File f = new File("city.txt");
		f.createNewFile();
		FileInputStream fis = new FileInputStream(f);
		// 定义一个字节缓冲区,该缓冲区的大小根据需要来定义
		byte[] buffer = new byte[fis.available()];
		// 循环来读取该文件中的数据
		size = fis.read(buffer);
		// 把字节数组转化成字符串
		content = new String(buffer, 0, size);
		// 关闭此文件输入流并释放与此流有关的所有系统资源。
		fis.close();
		Date start = null;
		if (StringUtil.isNotEmpty(content)) {
			start = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(content);
		}
		List<City> citys = cityService.getCitylist(start);
		if (citys.size() > 0) 
		{
			citys.stream().forEach(city -> {
				String d = city.getLastUpdate();
				d = d.substring(0, d.length() -2);
				city.setLastUpdate(d);
			});
			
			es.submit(new Runnable() {
				
				@Override
				public void run() {
					cityRepository.saveAll(citys);
				}
			});
			// 写入标记
			String bj = citys.get(0).getLastUpdate();
			System.out.println("写入city最新标记"+bj);
			FileOutputStream fos = new FileOutputStream("city.txt");
			// 必须转为字节数组才能写
			fos.write(String.valueOf(bj).getBytes());
			// 关闭此文件输出流并释放与此流有关的所有系统资源。此文件输出流不能再用于写入字节。 如果此流有一个与之关联的通道，则关闭该通道。
			fos.close();
		}
	}
}
